package com.ktg.mes.pro.controller;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ktg.common.core.page.TableDataInfo;
import com.ktg.common.utils.DateUtils;
import com.ktg.common.utils.StringUtils;
import com.ktg.mes.pro.domain.*;
import com.ktg.mes.pro.service.IProRouteProcessService;
import com.ktg.mes.pro.service.IProTaskService;
import com.ktg.mes.pro.service.IProWorkorderBomService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ktg.common.annotation.Log;
import com.ktg.common.core.controller.BaseController;
import com.ktg.common.core.domain.AjaxResult;
import com.ktg.common.enums.BusinessType;
import com.ktg.mes.pro.service.IProWorkorderService;
import com.ktg.common.utils.poi.ExcelUtil;

/**
 * 生产工单Controller
 *
 * @author yinjinlu
 * @date 2022-05-09
 */
@RestController
@RequestMapping("/mes/pro/workorder")
public class ProWorkorderController extends BaseController
{
    @Autowired
    private IProWorkorderService proWorkorderService;

    @Autowired
    private IProWorkorderBomService proWorkorderBomService;

    @Autowired
    private IProTaskService proTaskService;

    @Autowired
    private IProRouteProcessService proRouteProcesservice;

    /**
     * 查询生产工单列表
     */
    @PreAuthorize("@ss.hasPermi('mes:pro:workorder:list')")
    @GetMapping("/list")
    public AjaxResult list(ProWorkorder proWorkorder,
                           @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                           @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                           HttpServletRequest req)
    {
        QueryWrapper<ProWorkorder> queryWrapper = new QueryWrapper<>(proWorkorder);
        queryWrapper.orderByDesc("workorder_id");
        Page<ProWorkorder> page = new Page<>(pageNo,pageSize);
        queryWrapper.select("*,(SELECT quantity - COALESCE(quantity_not_in,0) as in_count FROM pro_task WHERE pro_task.workorder_id = pro_workorder.workorder_id ORDER BY create_time DESC LIMIT 1)");
        IPage<ProWorkorder> iPage = proWorkorderService.page(page,queryWrapper);
        return AjaxResult.success(iPage);
    }


    /**
     * 查询生产工单列表
     */
    @PreAuthorize("@ss.hasPermi('mes:pro:workorder:list')")
    @GetMapping("/needTasklist")
    public AjaxResult needTasklist(ProWorkorder proWorkorder)
    {
        List ins = new ArrayList<>();
        ins.add(ProTask.taskStatusDefect);
        ins.add(ProTask.taskStatusUnqualified);
        ins.add("待排产");

        QueryWrapper<ProWorkorder> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("status",ins);
        queryWrapper.orderByAsc("request_date");
        List<ProWorkorder> list = proWorkorderService.list(queryWrapper);
        return AjaxResult.success(list);
    }


    /**
     * 查询流水号
     */
    @PreAuthorize("@ss.hasPermi('mes:pro:workorder:list')")
    @GetMapping("/serialNumberList")
    public AjaxResult serialNumberList(){
        List<ProWorkorder> list = proWorkorderService.selectSerialNumberList();
        return AjaxResult.success(list);
    }

    /**
     * 查询生产工单流水号列表
     */
    @PreAuthorize("@ss.hasPermi('mes:pro:workorder:list')")
    @GetMapping("/tableList")
    public AjaxResult tableList(ProWorkorder proWorkorder){
        List<ProWorkorder> list = proWorkorderService.selectProWorkorderTableList(proWorkorder);
        return AjaxResult.success(list);
    }


    /**
     * 修改生产工单状态
     */
    @PreAuthorize("@ss.hasPermi('mes:pro:workorder:edit')")
    @PutMapping("/updateWorkorderState")
    public AjaxResult updateWorkorderState(@RequestBody ProWorkorder proWorkorder){

        return toAjax(proWorkorderService.updateWorkorderState(proWorkorder));
    }

    /**
     * 导出生产工单列表
     */
    @PreAuthorize("@ss.hasPermi('mes:pro:workorder:export')")
    @Log(title = "生产工单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ProWorkorder proWorkorder)
    {
        List<ProWorkorder> list = proWorkorderService.selectProWorkorderList(proWorkorder);
        ExcelUtil<ProWorkorder> util = new ExcelUtil<ProWorkorder>(ProWorkorder.class);
        util.exportExcel(response, list, "生产工单数据");
    }

    /**
     * 获取生产工单详细信息
     */
    @PreAuthorize("@ss.hasPermi('mes:pro:workorder:query')")
    @GetMapping(value = "/{workorderId}")
    public AjaxResult getInfo(@PathVariable("workorderId") Long workorderId)
    {
        return AjaxResult.success(proWorkorderService.selectProWorkorderByWorkorderId(workorderId));
    }


//    private static Lock lock = new ReentrantLock();

    /**
     * 新增生产工单
     */
    @PreAuthorize("@ss.hasPermi('mes:pro:workorder:add')")
    @Log(title = "生产工单", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ProWorkorder proWorkorder)
    {
//        lock.lock();
//        try {
//            if(UserConstants.NOT_UNIQUE.equals(proWorkorderService.checkWorkorderCodeUnique(proWorkorder))){
//                return AjaxResult.error("生产工单编号已存在！");
//            }

            if(proWorkorder.getParentId()==null || proWorkorder.getParentId()==0){
                proWorkorder.setAncestors("0");
            }

            if (proWorkorder.getStatus() == null){
                proWorkorder.setStatus(OrderStatus.scheduleWait.toName());
            }
            proWorkorderService.insertProWorkorder(proWorkorder);



            return AjaxResult.success(proWorkorder.getWorkorderId());
//        }catch (Exception e){
//            e.printStackTrace();
//        }finally {
//            lock.unlock();
//        }

//        return AjaxResult.error("操作失败");
    }

    /**
     * 修改生产工单
     */
    @PreAuthorize("@ss.hasPermi('mes:pro:workorder:edit')")
    @Log(title = "生产工单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ProWorkorder proWorkorder)
    {
        ProWorkorder workorder = proWorkorderService.selectProWorkorderByWorkorderId(proWorkorder.getWorkorderId());
        int ret =proWorkorderService.updateProWorkorder(proWorkorder);
        //如果是产品和数量发生变化则需要重新生成BOM组成
//        if(ret >0){
//            if(workorder.getProductId().longValue() != proWorkorder.getProductId().longValue() ||
//                    workorder.getQuantity().compareTo(proWorkorder.getQuantity())!=0){
//                removeBomLine(proWorkorder.getWorkorderId());
//                generateBomLine(proWorkorder.getWorkorderId());
//            }
//        }
        return toAjax(ret);
    }


    /**
     * 拆分工单
     */
    @PreAuthorize("@ss.hasPermi('mes:pro:workorder:add')")
    @Log(title = "拆分工单", businessType = BusinessType.INSERT)
    @PostMapping("/splitAdd")
    public AjaxResult splitAdd(@RequestBody ProWorkorder proWorkorder)
    {
        if (proWorkorder.getParentWorkorderId() == null || proWorkorder.getParentWorkorderId() == 0
                || proWorkorder.getParentTaskId() == null || proWorkorder.getParentTaskId() == 0 ){
            return AjaxResult.error("参数不足");
        }

        ProWorkorder oldOrder = proWorkorderService.getById(proWorkorder.getParentWorkorderId());
        if (proWorkorder.getQuantity().floatValue() > oldOrder.getQuantity().floatValue()){
            return AjaxResult.error("拆分数量过大，无法满足！");
        }

        ProTask oldTask = proTaskService.getById(proWorkorder.getParentTaskId());

        String routeId = String.valueOf(oldTask.getRouteId());
        String routeIndex = "0";
        if (oldTask.getProcessId() != null && oldTask.getProcessId() > 0){
            ProRouteProcess process = new ProRouteProcess();
            process.setRouteId(oldTask.getRouteId());
            process.setRecordId(oldTask.getProcessId());
            QueryWrapper<ProRouteProcess> proRouteProcessQueryWrapper = new QueryWrapper<>(process);
            List<ProRouteProcess> processes = proRouteProcesservice.list(proRouteProcessQueryWrapper);
            if (processes != null && processes.size() > 0){
                routeIndex = String.valueOf(processes.get(processes.size()-1).getOrderNum());
            }
        }

        if (!StringUtils.isEmpty(oldOrder.getParentRouteIdIds())){
            if (oldTask.getTaskId() != null){
                proWorkorder.setParentRouteIdIds(oldOrder.getParentRouteIdIds());
                proWorkorder.setParentRouteIndexs(oldOrder.getParentRouteIndexs());
            }else if(Integer.valueOf(routeIndex) > 0){
                proWorkorder.setParentRouteIdIds(oldOrder.getParentRouteIdIds()+","+routeId);
                proWorkorder.setParentRouteIndexs(oldOrder.getParentRouteIndexs()+","+routeIndex);
            }
        }else {
            if (oldTask.getTaskId() != null && Integer.valueOf(routeIndex) > 0){
                proWorkorder.setParentRouteIdIds(routeId);
                proWorkorder.setParentRouteIndexs(routeIndex);
            }

        }


        if(proWorkorder.getParentId()==null || proWorkorder.getParentId()==0){
            proWorkorder.setAncestors("0");
        }


        if (proWorkorder.getStatus() == null){
            proWorkorder.setStatus(OrderStatus.scheduleWait.toName());
        }
        proWorkorderService.insertProWorkorder(proWorkorder);


        oldOrder.setQuantity(BigDecimal.valueOf(oldOrder.getQuantity().floatValue()-proWorkorder.getQuantity().floatValue()));
        proWorkorderService.updateById(oldOrder);

        oldTask.setQuantity(BigDecimal.valueOf(oldTask.getQuantity().floatValue()-proWorkorder.getQuantity().floatValue()));
        proTaskService.updateById(oldTask);

        return AjaxResult.success(proWorkorder.getWorkorderId());

    }


    /**
     * 删除生产工单
     */
    @PreAuthorize("@ss.hasPermi('mes:pro:workorder:remove')")
    @Log(title = "生产工单", businessType = BusinessType.DELETE)
	@DeleteMapping("/{workorderIds}")
    public AjaxResult remove(@PathVariable Long[] workorderIds)
    {
        return toAjax(proWorkorderService.deleteProWorkorderByWorkorderIds(workorderIds));
    }




    /**
     * 修改生产工单
     */
    @PreAuthorize("@ss.hasPermi('mes:pro:workorder:edit')")
    @Log(title = "生产工单", businessType = BusinessType.UPDATE)
    @GetMapping("/getBatchCode")
    public AjaxResult getBatchCode(ProWorkorder proWorkorder)
    {
        ProWorkorder workorder = new ProWorkorder();
        workorder.setProductName(proWorkorder.getProductName());
        workorder.setViscosity(proWorkorder.getViscosity());
        workorder.setTagDate(proWorkorder.getTagDate());
        QueryWrapper<ProWorkorder> queryWrapper = new QueryWrapper<>(workorder);
        queryWrapper.last("limit 1");
        ProWorkorder findOne = proWorkorderService.getOne(queryWrapper);
        if (findOne == null){

            String str = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD,proWorkorder.getTagDate()).substring(2,10);
            String[] li = str.split("-");
            Integer year = Integer.valueOf(li[0]);
            Integer month = Integer.valueOf(li[1]);
            Integer day = Integer.valueOf(li[2]);

            String orderStr = null;

            if (day > 24){
                if (month > 12){
                    year = year+1;
                    month = 1;
                }else {
                    month = month+1;
                }
            }

            orderStr = year+""+(month>9? month:"0"+month);

            queryWrapper = new QueryWrapper<>();
            queryWrapper.select("batch_code");
            queryWrapper.like("batch_code",orderStr);
            queryWrapper.orderByDesc("batch_code");
            queryWrapper.ge("create_time",DateUtils.getDateByAddSecond(-60*24*3600));
            queryWrapper.last("limit 1");

            findOne =  proWorkorderService.getOne(queryWrapper);
            String um = null;
            if(findOne != null && findOne.getBatchCode().startsWith(orderStr)){
                um = findOne.getBatchCode().substring(4,findOne.getBatchCode().length());
                um = String.valueOf(Integer.valueOf(um).intValue()+1);
            }
            if (um == null){
                um = "001";
            }else if(um.length() == 1){
                um = "00"+um;
            }else if(um.length() == 2){
                um = "0"+um;
            }

            return AjaxResult.success(orderStr+um);
        }else {
            return AjaxResult.success(findOne.getBatchCode());
        }
    }



    /**
     * 删除当前工单下所有BOM组成
     * @param workorderId
     */
    private void removeBomLine(Long workorderId){
        ProWorkorderBom param = new ProWorkorderBom();
        param.setWorkorderId(workorderId);
        proWorkorderBomService.deleteProWorkorderBomByWorkorderId(workorderId);
    }

    @GetMapping("/TreeList")
    public TableDataInfo TreeList(){
        startPage();
        List<ProWorkorder> lists = proWorkorderService.TreeResul();
        return getDataTable(lists);
    }

}
